package com.guan.friend.manager;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.guan.common.core.constants.CacheConstants;
import com.guan.common.core.constants.Constants;
import com.guan.common.core.enums.ResultCode;
import com.guan.friend.domain.question.Question;
import com.guan.friend.mapper.question.QuestionMapper;
import com.guan.ojcommonredis.service.RedisService;
import com.guan.ojcommonsecurity.exception.ServiceException;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.security.Key;
import java.util.List;

@Component
public class QuestionCacheManager {

    @Resource
    private RedisService redisService;

    @Resource
    private QuestionMapper questionMapper;

    public Long getListSize(){
        return redisService.getListSize(CacheConstants.QUESTION_LIST);
    }

    /**
     * 从数据库中刷新缓存 将数据库中的题目 id (按照创建时间排序)放到 redis 的 list 中
     */
    public void refreshCache() {
        List<Question> questionList = questionMapper.selectList(new LambdaQueryWrapper<Question>()
                .select(Question::getQuestionId).orderByDesc(Question::getCreateTime));
        if(CollectionUtil.isEmpty(questionList)){
            return;
        }
        List<Long> questionIdList = questionList.stream().map(Question::getQuestionId).toList();
        redisService.rightPushAll(CacheConstants.QUESTION_LIST, questionIdList);
    }

    /**
     * 从缓存列表中得到当前题目（questionId）的前一题
     * @param questionId
     * @return
     */
    public Long preQuestion(Long questionId) {
        Long index = redisService.indexOfList(CacheConstants.QUESTION_LIST, questionId);
        if(index == 0){
            throw new ServiceException(ResultCode.FAILED_NO_PRE);
        }
        return redisService.indexList(CacheConstants.QUESTION_LIST, index - 1, Long.class);
    }

    public Long nextQuestion(Long questionId) {
        Long index = redisService.indexOfList(CacheConstants.QUESTION_LIST, questionId);
        long lastIndex = getListSize() - 1;
        if(index == lastIndex){
            throw new ServiceException(ResultCode.FAILED_NO_NEXT);
        }
        return redisService.indexList(CacheConstants.QUESTION_LIST, index + 1, Long.class);
    }

    public Long getHostListSize() {
        return redisService.getListSize(CacheConstants.QUESTION_HOST_LIST);
    }

    public void refreshHotQuestionList(List<Long> hotQuestionIdList) {
        if (CollectionUtil.isEmpty(hotQuestionIdList)) {
            return;
        }
        redisService.rightPushAll(CacheConstants.QUESTION_HOST_LIST, hotQuestionIdList);

    }

    public List<Long> getHostList() {
        return redisService.getCacheListByRange(CacheConstants.QUESTION_HOST_LIST,
                CacheConstants.DEFAULT_START, CacheConstants.DEFAULT_END, Long.class);

    }
}
